//
//  SearchDetail.m
//  CarHome
//
//  Created by 蒋寒霄 on 14-9-24.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "SearchDetail.h"
//CustomCell
#import "SeriesSearchDetailCell.h"
#import "SpeclistModelCell.h"
#import "ImgModelCell.h"
#import "NatureModelCell.h"
//CustomVC
#import "RecommendWebVC.h"
//ThirdParty
#import "UIImageView+WebCache.h"
//cell重用池
NSString *const detail_searchDetail = @"SearchDetailTableViewCell";
NSString *const speclist_searchDetail = @"SpclistTableViewCell";
NSString *const imgmodel_searchDetail = @"imgModelTableViewCell";
NSString *const naturemodel_searchDetail = @"natureModelTableCell";
@implementation SearchDetail
- (void)dealloc
{
    [_seriesmodel release];
    _seriesmodel = nil;
    [_speclistModel release];
    _speclistModel = nil;
    [_imgmodel release];
    _imgmodel = nil;
    [_naturemodel release];
    _naturemodel = nil;
    [_nextURL release];
    _nextURL = nil;
    
    [_name release];
    _name = nil;
    [_searchNum release];
    _searchNum = nil;
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _seriesmodel = [[NSMutableDictionary alloc] init];
        _speclistModel = [[NSMutableArray alloc] init];
        _imgmodel = [[NSMutableDictionary alloc] init];
        _naturemodel = [[NSMutableArray alloc] init];
        _nextURL = [[NSMutableString alloc] init];
        self.name = [[NSMutableString alloc] init];
        self.searchNum = [[NSMutableString alloc] init];
    }
    return self;
}
#pragma mark -
#pragma mark createTableView
- (void)createTableView
{
    _searchTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _searchTableView.delegate = self;
    _searchTableView.dataSource = self;
    [_searchTableView registerClass:[SeriesSearchDetailCell class] forCellReuseIdentifier:detail_searchDetail];
    [_searchTableView registerClass:[SpeclistModelCell class] forCellReuseIdentifier:speclist_searchDetail];
    [_searchTableView registerClass:[ImgModelCell class] forCellReuseIdentifier:imgmodel_searchDetail];
    [_searchTableView registerClass:[NatureModelCell class] forCellReuseIdentifier:naturemodel_searchDetail];
    [_searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self addSubview:_searchTableView];
    [_searchTableView release];
}

- (void)layoutSubviews
{
    _searchTableView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}

#pragma mark -
#pragma mark SearchDetailRefresh 上拉加载下拉刷新
- (void)setupSearchDetailRefresh
{
    [_searchTableView addHeaderWithTarget:self action:@selector(headerChannelRefresh)];
    [_searchTableView headerBeginRefreshing];// 程序开始就刷新
    [_searchTableView addFooterWithTarget:self action:@selector(footChannelRefresh)];
    
    _searchTableView.headerPullToRefreshText = @"下拉刷新";
    _searchTableView.headerReleaseToRefreshText = @"释放刷新";
    _searchTableView.headerRefreshingText = @"正在刷新中···";
    _searchTableView.footerPullToRefreshText = @"上拉加载";
    _searchTableView.footerReleaseToRefreshText = @"释放加载";
    _searchTableView.footerRefreshingText = @"正在加载中···";
}
#pragma mark 上拉刷新加载方法
- (void)headerChannelRefresh
{
    [self connectRefresh:_firstURL];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_searchTableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_searchTableView headerEndRefreshing];
       
    });
}
static int p = 1;
- (void)footChannelRefresh
{
    NSRange subStr = [_nextURL rangeOfString:[NSString stringWithFormat:@"p=%d", p]];
    p++;
    if (subStr.location != NSNotFound) {
        [_nextURL replaceCharactersInRange:subStr withString:[NSString stringWithFormat:@"p=%d",p]];
    }
    [self connectUpload:_nextURL];
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_searchTableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_searchTableView footerEndRefreshing];
       
    });
}

#pragma mark -
#pragma mark tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 110;
    }
    if (indexPath.section == 1) {
        return 60;
    }
    if (indexPath.section == 2) {
        return 147;
    }
    if (indexPath.section == 3) {
        return 65;
    }
    return 100;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return [_speclistModel count];
    }
    if (section == 3) {
        return [_naturemodel count];
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        SeriesSearchDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:detail_searchDetail];
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[_seriesmodel objectForKey:@"img"]] placeholderImage:[UIImage imageNamed:@"Loading.png"]];
        cell.name.text = [_seriesmodel objectForKey:@"name"];
        cell.price.text = [_seriesmodel objectForKey:@"pricebetween"];
        cell.grade.text = [_seriesmodel objectForKey:@"koubeiscore"];
        CGFloat width = [cell.grade.text floatValue] * 100 / 5;
        cell.centre.frame = CGRectMake(cell.price.frame.origin.x, cell.price.frame.origin.y + cell.price.frame.size.height + 10, width, 20);
        return cell;
    }
    if (indexPath.section == 1) {
        SpeclistModelCell *cell = [tableView dequeueReusableCellWithIdentifier:speclist_searchDetail];
        cell.title.text = [[_speclistModel objectAtIndex:indexPath.row] objectForKey:@"name"];
        cell.price.text = [[_speclistModel objectAtIndex:indexPath.row] objectForKey:@"lowprice"];
        return cell;
    }
    if (indexPath.section == 2) {
        ImgModelCell *cell = [tableView dequeueReusableCellWithIdentifier:imgmodel_searchDetail];
        NSArray *imglist = [_imgmodel objectForKey:@"imglist"];
        if ([_name isEqualToString:@""] == NO) {
            cell.title.text = [NSString stringWithFormat:@"%@图片", _name] ;
        }
        [cell.leftImg sd_setImageWithURL:[NSURL URLWithString:[[imglist firstObject] objectForKey:@"img"]] placeholderImage:[UIImage imageNamed:@"Loading.png"]];
        [cell.centerImg sd_setImageWithURL:[NSURL URLWithString:[[imglist objectAtIndex:1] objectForKey:@"img"]] placeholderImage:[UIImage imageNamed:@"Loading.png"]];
        [cell.rightImg sd_setImageWithURL:[NSURL URLWithString:[[imglist lastObject] objectForKey:@"img"]] placeholderImage:[UIImage imageNamed:@"Loading.png"]];
        cell.moreTitle.text = [NSString stringWithFormat:@"共%@图片,详情页查看更多", [_imgmodel objectForKey:@"imgcount"]];
        return cell;
    }
    if (indexPath.section == 3) {
        NatureModelCell *cell = [tableView dequeueReusableCellWithIdentifier:naturemodel_searchDetail];
        NSDictionary *dictionary = [_naturemodel objectAtIndex:indexPath.row];
        /*
         *UILabel显示不同的字体和颜色,用NSMutableAttributedString
         *1.找到NSRange ,<B>和</B>的位置
         *2.创建NSMutableAttributedString对象
         *3.判断范围是否找到
         */
        //1.
        NSRange first = [[dictionary objectForKey:@"title"] rangeOfString:@"<B>"];
        NSRange second = [[dictionary objectForKey:@"title"] rangeOfString:@"</B>"];
        //2.
        NSMutableAttributedString * textStr= [[NSMutableAttributedString alloc] initWithString:[dictionary objectForKey:@"title"]];
        [textStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(first.location + first.length, second.location - (first.location + first.length))];
        [textStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:18] range:NSMakeRange(first.location + first.length, second.location - (first.location + first.length))];
        //3.
        if (second.location != NSNotFound) {
            [textStr replaceCharactersInRange:second withString:@""];
        }
        if (first.location != NSNotFound) {
            [textStr replaceCharactersInRange:first withString:@""];
        }
        cell.title.attributedText = textStr;
        [textStr release];
        
        cell.indexdetil.text = [dictionary objectForKey:@"indexdetail"];
        cell.time.text = [dictionary objectForKey:@"time"];
        if ([[dictionary objectForKey:@"mediatype"] intValue] == 2) {
            cell.type.text = @"说客";
            cell.type.backgroundColor = [UIColor orangeColor];
        }
        if ([[dictionary objectForKey:@"mediatype"] intValue] == 3) {
            cell.type.text = @"视频";
            cell.type.backgroundColor = [UIColor redColor];
        }
        cell.replycount.text = [NSString stringWithFormat:@"%d评论", [[dictionary objectForKey:@"replycount"] intValue]];
        
        return cell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 3) {
        NSString *titleHeader = [[NSString alloc] initWithFormat:@"找到%@条相关结果", self.searchNum];
        return titleHeader;
    }
    return NULL;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSString * title = [_seriesmodel objectForKey:@"name"];
        NSString *cardId = [_seriesmodel objectForKey:@"hotspecid"];
        NSString *specitem = [_seriesmodel objectForKey:@"koubeicount"];
        self.styleBlock(cardId, specitem, title);
    }
    if (indexPath.section == 1) {
        NSString *title = [[_speclistModel objectAtIndex:indexPath.row] objectForKey:@"name"];
        NSString *cardId = [[_speclistModel objectAtIndex:indexPath.row] objectForKey:@"id"];
        NSString *specitem = @"0";
        self.styleBlock(cardId, specitem, title);
    }
    if (indexPath.section == 3) {
        NSString *url = [[NSString alloc] init];
        int mediatype = [[[_naturemodel objectAtIndex:indexPath.row] objectForKey:@"mediatype"] intValue];
        if (mediatype == 2) {
            url = [NSString stringWithFormat:shuokeContentURL, [[[_naturemodel objectAtIndex:indexPath.row] objectForKey:@"id"] intValue]];
        }
        if (mediatype == 5) {
            url = [NSString stringWithFormat:forumContentURL, [[[_naturemodel objectAtIndex:indexPath.row] objectForKey:@"id"] intValue]];
        }
        if (mediatype == 1) {
            url = [NSString stringWithFormat:NewsContentURL, [[[_naturemodel objectAtIndex:indexPath.row] objectForKey:@"id"] intValue]];
        }
        if (mediatype == 3) {
            url = [NSString stringWithFormat:videosContentURL, [[[_naturemodel objectAtIndex:indexPath.row] objectForKey:@"id"] intValue]];
        }
        self.block(url);
    }
}

#pragma mark -
#pragma mark 方法传值
- (void)setResultDictionary:(NSDictionary *)dic url:(NSString *)strUrl
{
    _name = [[dic objectForKey:@"matchname"] retain];
    _searchNum = [[dic objectForKey:@"rowcount"] retain];
    _seriesmodel = [[dic objectForKey:@"seriesmodel"] retain];
    [_speclistModel addObjectsFromArray:[dic objectForKey:@"speclistmodel"]];
    _imgmodel = [[dic objectForKey:@"imgmodel"] retain];
    [_naturemodel addObjectsFromArray:[dic objectForKey:@"naturemodel"]];
    _firstURL = [[NSString alloc] initWithString:strUrl];
    _nextURL = [[NSMutableString alloc] initWithString:strUrl];
    [self createTableView];
    [self setupSearchDetailRefresh];
    [_searchTableView reloadData];
}
#pragma mark 上拉刷新网络请求
- (void)connectRefresh:(NSString *)strURL
{
    [NetUrl connect:strURL parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
        _name = [[dic objectForKey:@"matchname"] retain];
        _searchNum = [[dic objectForKey:@"rowcount"]retain];
        _seriesmodel = [[dic objectForKey:@"seriesmodel"] retain];
        if ([_speclistModel count] != 0) {
            [_speclistModel removeAllObjects];
        }
        [_speclistModel addObjectsFromArray:[dic objectForKey:@"speclistmodel"]];
        _imgmodel = [[dic objectForKey:@"imgmodel"] retain];
        if ([_naturemodel count] != 0) {
            [_naturemodel removeAllObjects];
        }
        [_naturemodel addObjectsFromArray:[dic objectForKey:@"naturemodel"]];
//        [_searchTableView headerEndRefreshing];
//        [_searchTableView footerEndRefreshing];
//        [_searchTableView reloadData];
    }];
}
#pragma mark 下拉加载网络请求
- (void)connectUpload:(NSString *)strURL
{
    [NetUrl connect:strURL parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
        [_naturemodel addObjectsFromArray:[dic objectForKey:@"naturemodel"]];
//        [_searchTableView headerEndRefreshing];
//        [_searchTableView footerEndRefreshing];
//        [_searchTableView reloadData];
    }];
}

#pragma mark -
#pragma mark 1.block的set方法
- (void)setSearchDetailBlock:(SearchDetailBlock)block
{
    self.block = block;
}
- (void)setSearchStyleBlock:(SearchStyleBlock)styleBlock
{
    self.styleBlock = styleBlock;
}

@end
